package com.zhenhunfan.io.model.aio.demo02;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>Title: Server</p>
 * <p>Description: </p>
 *
 * @author zhenhunfan
 * @version 1.0.0
 * @date 2021/4/6
 */
public class Server {
    public static void main(String[] args) throws IOException, InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        AsynchronousChannelGroup threadGroup = AsynchronousChannelGroup.withCachedThreadPool(executorService,1);

        AsynchronousServerSocketChannel serverchannel = AsynchronousServerSocketChannel.open(threadGroup)
                .bind(new InetSocketAddress(8888));

        serverchannel.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {

            /**
             * 客户端连接成功时触发调用，回调函数的感觉
             * @param client
             * @param attachment
             */
            @Override
            public void completed(AsynchronousSocketChannel client, Object attachment) {
                //不执行下面的代码，下一个连接就连不上来了
                serverchannel.accept(null, this);
                try {
                    System.out.println(client.getRemoteAddress());
                    ByteBuffer buffer = ByteBuffer.allocate(1024);


                    client.read(buffer, buffer, new CompletionHandler<Integer, ByteBuffer>() {

                        /**
                         * 有读的数据的时候调用，也是个回调函数的感觉
                         * @param result
                         * @param attachment
                         */
                        @Override
                        public void completed(Integer result, ByteBuffer attachment) {
                            attachment.flip();
                            System.out.println(new String(attachment.array(), 0, result));
                            client.write(ByteBuffer.wrap("Hello Client".getBytes()));
                        }

                        @Override
                        public void failed(Throwable exc, ByteBuffer attachment) {
                            exc.printStackTrace();
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void failed(Throwable exc, Object attachment) {
                exc.printStackTrace();
            }
        });
        while (true) {
            Thread.sleep(1000);
        }
    }
}
